#include<iostream>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

using namespace std;

void Usage(string proc)
{
    cout<<"\n\rUsage"<<proc<<"serverip serverport "<<endl;
}
struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    string serverip;
};

void* recv_message(void* argc)
{
    ThreadData* td=static_cast<ThreadData*>(argc);
    char buffer[1024];
    while(true)
    {
        struct sockaddr_in tmp;
        socklen_t len=sizeof(tmp);
        ssize_t s=recvfrom(td->sockfd,buffer,1023,0,(struct sockaddr*)&tmp,&len);
        if(s<0)
        {
            buffer[s]=0;
            cout<<buffer<<endl;
        }

    }
}
void* sender_meaasge(void* argc)
{
    ThreadData* td=static_cast<ThreadData*>(argc);
    string message;
    ssize_t len=sizeof(td->server);
    string welcome;
    welcome=td->serverip;
    welcome+="comming...";
    sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->server),len);
    while(true)
    {
        cout<<"please@";
        getline(cin,message);
        
    }
}


//多线程
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);

    }
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);
    
    struct ThreadData td;
    //struct sockaddr_in server;
    bzero(&td.server,sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);//需要保证我的端口号是网络字节序列，因为该端口号要给对方发送的
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd <0)
    {
	    cout << "socket err " << endl;
	    return 1;
    }


   
    pthread_t recvr,sender;
    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,sender_meaasge,&td);

    //pthread_join();

}